using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Light.Assets.Scripts.EventManager;
using Refresh;
using UnityEngine;
using UnityEngine.UI;

namespace Light
{
    public class GoodsJsonData
    {
        /// <summary>
        ///     ��������
        /// </summary>
        public int count;

        /// <summary>
        ///     ��ScriptObject�б�ǵ�Id
        /// </summary>
        public int id;

        /// <summary>
        ///     ��QuickSlot�е������
        /// </summary>
        public int index = 0;

        /// <summary>
        ///     ʹ��guid���ɵ�Ψһid
        /// </summary>
        public string uId;
    }

    public class GoodsJsonListData
    {
        public List<GoodsJsonData> data = new(); //�����е���Ʒ�б�

        public List<GoodsJsonData> itemsEquipData = new(); //�Ѿ�����װ������item
    }

    public class GoodsController : BasePanel
    {
        /// <summary>
        ///     װ���������е�����չʾ
        /// </summary>
        public GameObject itemEquipUI;

        /// <summary>
        ///     �޸�item�����Ĺ�������
        /// </summary>
        public ItemDetails itemParamsChangeUI;

        /// <summary>
        ///     װ����ĿҲ��Ҫ���е���
        /// </summary>
        private readonly Dictionary<ItemType, GameObject> EquipTagDic = new();

        private readonly Dictionary<AbstractItemSO, GameObject> itemsDic = new();

        /// <summary>
        ///     ����ͬ���͵�item���뵽goods�з���ʹ��
        /// </summary>
        private readonly Dictionary<ItemType, GameObject> ScrollViewTagDic = new();

        /// <summary>
        ///     �����������������
        /// </summary>
        private GameObject contentUI;

        private VerticalLayoutGroup EquipVLG;

        //item�б�����Ĵ�С
        public (Vector2, Vector2) itemContentUIArea;

        //itemװ���������С
        public (Vector2, Vector2) itemEuqipUIArea;

        /// <summary>
        ///     �����������
        /// </summary>
        private GameObject itemListUI;

        //item��Ԥ�Ƽ�
        private GameObject itemPrefab;

        //��Goods�еķ�����
        private GameObject scrollViewTagPrefab;

        private VerticalLayoutGroup scrollViewVLG;

        private void Awake()
        {
            itemListUI = transform.Find("LeftBar").gameObject;
            //��ȡ����λ��
            contentUI = transform.Find("LeftBar/Scroll View/Viewport/Content").gameObject;

            itemEquipUI = transform.Find("RightBar/RightTopBar").gameObject;

            itemParamsChangeUI = transform.Find("RightBar/RightBottomBar/ItemDetails").GetComponent<ItemDetails>();

            scrollViewVLG = contentUI.GetComponent<VerticalLayoutGroup>();

            EquipVLG = itemEquipUI.GetComponent<VerticalLayoutGroup>();
        }

        public override async void Init()
        {
            //�ȴ�Ԥ�Ƽ��������
            await LoadPrefabByAddressAbleAsync();

            MouseDragAreaInit();

            CreateItemTagObject();

            //����GoodsItems�б���ʼ���¼�
            //�ӳ��л�ȡ
            var evt = StatusBarEvent.Get();

            evt.BarType = FunctionBarType.Goods;
            evt.BarOperationType = FunctionBarOperationType.Init;

            //�������򻮷�
            //Ҫ�����е�����ȫ���������
            evt.contentTypes = new List<FunctionBarContentType>
                { FunctionBarContentType.GoodsScrollView, FunctionBarContentType.GoodsItemEuqip };

            //�����¼�
            EventManager.SendEvent(evt);
        }

        /// <summary>
        ///     ʹ��addressable����prefab
        /// </summary>
        /// <returns></returns>
        private async Task LoadPrefabByAddressAbleAsync()
        {
            ResManager.Instance.LoadAsync<GameObject>("Item", obejct => { itemPrefab = obejct; },
                LoadType.AddressAbles);

            ResManager.Instance.LoadAsync<GameObject>("ScrollViewTag", obejct => { scrollViewTagPrefab = obejct; },
                LoadType.AddressAbles);

            await UniTask.WaitUntil(() => itemPrefab != null);

            await UniTask.WaitUntil(() => scrollViewTagPrefab != null);
        }

        /// <summary>
        ///     ��ǰ�ڶ�Ӧλ���Ͻ�������
        /// </summary>
        private void CreateItemTagObject()
        {
            foreach (ItemType item in Enum.GetValues(typeof(ItemType)))
            {
                var go = Instantiate(scrollViewTagPrefab, contentUI.transform);
                var go1 = Instantiate(scrollViewTagPrefab, itemEquipUI.transform);

                var tagName_cn = "";
                switch (item)
                {
                    case ItemType.Weapon:
                        tagName_cn = "����";
                        break;
                    case ItemType.Prop:
                        tagName_cn = "����";
                        break;
                }

                go.GetComponentInChildren<Text>().text = tagName_cn;
                go1.GetComponentInChildren<Text>().text = tagName_cn;

                //��ʼ������Ĭ��ȫ��false
                go.SetActive(false);
                go1.SetActive(false);

                ScrollViewTagDic.Add(item, go);

                EquipTagDic.Add(item, go1);
            }
        }

        /// <summary>
        ///     �ù���ģ���������position����
        /// </summary>
        private void MouseDragAreaInit()
        {
            //����UI��С�����������ק���
            var rectransfrom = itemEquipUI.transform as RectTransform;
            var w = rectransfrom.rect.width;
            var h = rectransfrom.rect.height;
            var x = rectransfrom.position.x;
            var y = rectransfrom.position.y;
            var xL = x - w / 2;
            var xR = x + w / 2;
            var yL = y - h / 2;
            var yR = y + h / 2;

            itemEuqipUIArea.Item1 = new Vector2(xL, xR);
            itemEuqipUIArea.Item2 = new Vector2(yL, yR);

            rectransfrom = itemListUI.transform as RectTransform;
            w = rectransfrom.rect.width;
            h = rectransfrom.rect.height;
            x = rectransfrom.position.x;
            y = rectransfrom.position.y;
            xL = x - w / 2;
            xR = x + w / 2;
            yL = y - h / 2;
            yR = y + h / 2;

            itemContentUIArea.Item1 = new Vector2(xL, xR);
            itemContentUIArea.Item2 = new Vector2(yL, yR);
        }

        public override void Refresh<T>(T info)
        {
            base.Refresh(info);

            var data = info as StatusBarInfo;

            foreach (var item in data.operations)
                if (item.Item2 == FunctionBarOperationType.Add)
                    ItemAdd(data, item);
                else if (item.Item2 == FunctionBarOperationType.Delete) ItemDelete(data, item);

            //LayoutRebuilder.ForceRebuildLayoutImmediate(GetComponent<RectTransform>());
            ////ǿ��ˢ�²���
            //this.scrollViewVLG.CalculateLayoutInputVertical();
            //this.EquipVLG.CalculateLayoutInputVertical();
            //Canvas.ForceUpdateCanvases();
        }

        private void CheckShouldActiveFalse(GameObject target)
        {
            if (target.transform.parent.childCount == 2) target.transform.parent.gameObject.SetActive(false);
        }

        private void ItemAdd(StatusBarInfo data, (FunctionBarData, FunctionBarOperationType) operation)
        {
            var temp = operation.Item1 as GoodsBarData;

            //׼��ʵ��������Ϸ����
            GameObject go = null;

            GameObject parentGo = null;

            //��ѡ���ʵ�item������
            if (data.contentType == FunctionBarContentType.GoodsScrollView)
                ScrollViewTagDic.TryGetValue(temp.type, out parentGo);
            else if (data.contentType == FunctionBarContentType.GoodsItemEuqip)
                EquipTagDic.TryGetValue(temp.type, out parentGo);
            //��Ԫ�ط�������
            parentGo.SetActive(true);

            itemsDic.TryGetValue(temp.data, out go);
            if (go != null)
            {
                CheckShouldActiveFalse(go); //����Ƿ�Ӧ�ø�����active����Ϊfalse
                go.transform.SetParent(parentGo.transform);
                var tempItem = go.GetComponent<Item>();
                tempItem.Init(this, data.contentType);
                return;
            }

            //ʵ����Item��Ϸ����
            go = Instantiate(itemPrefab, parentGo.transform);

            //���ڻ�Լ���װ������������������ ,//TODO���������
            itemsDic.TryAdd(temp.data, go);

            //Itemע������

            //����Panel������Ϊ���������ܵĵ��÷�ʽ
            var tempItemOut = go.GetComponent<Item>();

            tempItemOut.Init(this, data.contentType);

            //��ÿһ��Item��������
            var evt = ItemRefreshData.Get();

            evt.type = FunctionBarOperationType.Add;
            evt.data = temp.data;

            //TODO��������Ҫ�������
            go.GetComponent<IRefresh>().Refresh(evt);
        }

        /// <summary>
        ///     ִ��ɾ������
        /// </summary>
        /// <param name="data"></param>
        /// <param name="operation"></param>
        private void ItemDelete(StatusBarInfo data, (FunctionBarData, FunctionBarOperationType) operation)
        {
            //ɾ���������Ѿ�װ����Item
            //���ڴ洢�Ķ���һ��ģ�ֱ����
            var temp = operation.Item1 as GoodsBarData;
            itemsDic.TryGetValue(temp.data, out var res);

            //�ݻٶ���
            Destroy(res);
            //�Ƴ�����
            itemsDic.Remove(temp.data);
        }

        /// <summary>
        ///     ����Panel�ٴδ򿪵���Ϣ
        /// </summary>
        public override void ReOpen()
        {
            using var evt = GoodsPanelReOpenEvent.Get();
            EventManager.SendEvent(evt);
        }

        public void DeleteGameObject(AbstractItemSO item)
        {
            itemsDic.Remove(item);
        }
    }
}